package com.midongtech.news;

import android.app.ActivityManager;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;


public class AppUtils {

    private static final String TAG = "AppUtils";

    private static String sLastTopApp = "";
    private static String sLastTopAppActivity = "";



    public static void startApp(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return;
        }
        try {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("hyw", "startApp Exception:" + e.getMessage());
        }
    }


    // 将Unix时间戳转变为日期，如调用TimeStampToDate("1252639886", "yyyy-MM-dd
    // HH:mm:ss")返回值：2009-11-09 11:31:26

    public static boolean isAppInstalled(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            if (info == null) {
                return false;
            } else {
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }



    /**
     * 判断当前设备中有没有“有权查看使用权限的应用”这个选项
     *
     * @param context
     * @return
     */
    public static boolean hasOption(Context context) {
        PackageManager packageManager = context.getApplicationContext()
                .getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    /**
     * 判断调用该设备中“有权查看使用权限的应用”这个选项的APP有没有打开
     */
    public static boolean isSwitchOpen(Context context) {
        long ts = System.currentTimeMillis();
        UsageStatsManager usageStatsManager = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            usageStatsManager = (UsageStatsManager) context.getApplicationContext()
                    .getSystemService(Context.USAGE_STATS_SERVICE);
        }
        if (usageStatsManager == null)
            return false;
        List<UsageStats> queryUsageStats = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            queryUsageStats = usageStatsManager.queryUsageStats(
                    UsageStatsManager.INTERVAL_BEST, 0, ts);
        }
        if (queryUsageStats != null && queryUsageStats.size() > 0)
            return true;
        else return false;
    }

    public static boolean isUsagePermissionAceess(Context context) {
        boolean isAccess = true;
        if (Build.VERSION.SDK_INT >= 21) {
            if (hasOption(context)) {
                return isSwitchOpen(context);
            }
        }
       return isAccess;
    }



    public static String[] getTopAppInfo(Context context) {
        String[] info = new String[]{sLastTopApp, sLastTopAppActivity};
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> appTasks = activityManager.getRunningTasks(1);
            if (null != appTasks && !appTasks.isEmpty()) {
                info[0] = appTasks.get(0).topActivity.getPackageName();
                info[1] = appTasks.get(0).topActivity.getClassName();
                return info;
            }
        } else {
            long endTime = System.currentTimeMillis();
            long beginTime = endTime - 1 * 60 * 1000;
            UsageStatsManager manager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            String result = "";
            String resultActivity = "";
            UsageEvents.Event event = new UsageEvents.Event();
            UsageEvents usageEvents = manager.queryEvents(beginTime, endTime);
            while (usageEvents.hasNextEvent()) {
                usageEvents.getNextEvent(event);
                if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                    result = event.getPackageName();
                    resultActivity = event.getClassName();
                }
            }
            if (!TextUtils.isEmpty(result)) {
                sLastTopApp = result;
            }
            if (!TextUtils.isEmpty(resultActivity)) {
                sLastTopAppActivity = resultActivity;
            }
            info[0] = sLastTopApp;
            info[1] = sLastTopAppActivity;
            return info;
        }
        return info;
    }



    public static boolean openDeepLink(Context ctx, String url) {
        try {
            Intent intent1 = new Intent();
            intent1.setAction("android.intent.action.VIEW");
            Uri uri = Uri.parse(url);
            intent1.setData(uri);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ctx.startActivity(intent1);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }




}
